package com.snowyee.snowyeecodesandbox.service;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.snowyee.snowyeecodesandbox.model.ExecuteCodeRequest;
import com.snowyee.snowyeecodesandbox.model.ExecuteCodeResponse;
import com.snowyee.snowyeecodesandbox.model.ExecuteMessage;
import com.snowyee.snowyeecodesandbox.model.JudgeInfo;
import com.snowyee.snowyeecodesandbox.utils.ProcessUtils;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Slf4j
public abstract class JavaCodeSandboxTemplate implements CodeSandbox{


    private static final String GLOBAL_CODE_DIR_NAME = "tmpCode";

    private static final String GLOBAL_JAVA_CLASS_NAME = "Main.java";

    // 用户当前目录
    private String userDir = System.getProperty("user.dir");
    //
    private String globalCodePathName = userDir + File.separator + GLOBAL_CODE_DIR_NAME;


    protected String userCodeParentPath = globalCodePathName + File.separator + UUID.randomUUID();

    /**
     * 1、把用户的代码保存为文件
     * @return
     */
    public File saveCodeToFile(String code){

        // 判断全局代码目录是否存在，不存在则新建
        if (!FileUtil.exist(globalCodePathName)){
            FileUtil.mkdir(globalCodePathName);
        }

        // 用户存放的代码进行隔离
        String userCodePath = userCodeParentPath + File.separator + GLOBAL_JAVA_CLASS_NAME;
        File userCodeFile = FileUtil.writeString(code, userCodePath, StandardCharsets.UTF_8);

        return userCodeFile;
    }

    /**
     * 2、编译代码得到class文件
     * @param userCodeFile
     * @return
     */
    public ExecuteMessage compileCode(File userCodeFile){
        String compileCmd = String.format("javac -encoding utf-8 %s",userCodeFile.getAbsolutePath());
        ExecuteMessage compileMessage = ProcessUtils.getProcessMessage(compileCmd,"编译");
        System.out.println(compileMessage);
        return compileMessage;
    }

    /**
     * 3、运行代码得到输出结果
     * @param inputList
     * @return
     */
    public List<ExecuteMessage> runCode(List<String> inputList){
        List<ExecuteMessage> executeMessages = new ArrayList<>();
        for (String inputArgs : inputList){
            // 需要限制运行代码需要的最大内存
            String runCmd = String.format("java -Xmx256m -Dfile.encoding=UTF-8 -cp %s Main %s",userCodeParentPath,inputArgs);
            ExecuteMessage runMessage = ProcessUtils.getProcessMessage(runCmd,"运行");
//                Process compileProcess = Runtime.getRuntime().exec(runCmd);
//                ExecuteMessage compileMessage = ProcessUtils.getInterActionProcessMessage(compileProcess,"运行",inputArgs);
            System.out.println(runMessage);
            executeMessages.add(runMessage);
        }

        return executeMessages;
    }



    /**
     * 4、收集整理的输出结果
     * @param executeMessages
     * @return
     */
    public ExecuteCodeResponse getOutPutResponse(List<ExecuteMessage> executeMessages){
        // 判断运行时间是否超时
        long maxTime = 0;
        long maxMemory = 0;
        ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
        List<String> outputList = new ArrayList<>();
        for (ExecuteMessage executeMessage : executeMessages){
            String errorMessage = executeMessage.getErrorMessage();
            if (StrUtil.isNotBlank(errorMessage)){
                executeCodeResponse.setMessage(errorMessage);
                // 表示运行错误，比如程序运行失败的信息
                executeCodeResponse.setStatus("3");
                break;
            }
            long time = executeMessage.getTime();
            if (time > maxTime){
                maxTime = time;
            }
            long memory = executeMessage.getMemory();
            if (memory > maxMemory){
                maxMemory = memory;
            }
            // 正常运行完成
            executeCodeResponse.setStatus("1");
            // 6、错误处理，提成程序的健壮性
            if (executeMessage.getStatus() != null && executeMessage.getStatus() == 2){
                // 沙箱错误，可能是编译出现错误
                executeCodeResponse.setStatus("2");
            }

            outputList.add(executeMessage.getMessage());
        }
        executeCodeResponse.setOutputList(outputList);
        JudgeInfo judgeInfo = new JudgeInfo();
        // 获取最大运行时间
        judgeInfo.setTime(maxTime);
        judgeInfo.setMemory(maxMemory);
        executeCodeResponse.setJudgeInfo(judgeInfo);

        return executeCodeResponse;
    }

    /**
     * 5、删除临时文件
     */
    public boolean deleteFile(File userCodeFile){
        if (userCodeFile.getParentFile()!=null){
            boolean del = FileUtil.del(userCodeFile.getParentFile());
            System.out.println("删除"+(del?"成功":"失败"));
            return del;
        }
        return true;
    }


    @Override
    public ExecuteCodeResponse executeCode(ExecuteCodeRequest executeCodeRequest) {
//        System.setSecurityManager(new DenySecurityManager());
        List<String> inputList = executeCodeRequest.getInputList();
        String code = executeCodeRequest.getCode();
        String language = executeCodeRequest.getLanguage();

        // 1、把用户的代码保存为文件
        File userCodeFile = saveCodeToFile(code);

        System.out.println(userCodeFile.getAbsolutePath());
        // 2、编译代码得到class文件
        ExecuteMessage compileMessage= compileCode(userCodeFile);

        // 3、运行代码得到输出结果
        List<ExecuteMessage> executeMessages = runCode(inputList);

        // 4、收集整理的输出结果
        ExecuteCodeResponse executeCodeResponse = getOutPutResponse(executeMessages);

        // 5、删除临时文件
        boolean deleteFile = deleteFile(userCodeFile);
        if (!deleteFile){
            log.error("deleteFile error , userCodeFilePath = {}", userCodeFile.getAbsolutePath());
        }

        return executeCodeResponse;
    }
}
